package zh.dummy.netty.core.codec;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;

public class FastjsonDecoder {
	
	protected JSONObject decode(ByteBuf in) {
		
		byte[] buffer = new byte[in.readableBytes()];
		in.readBytes(buffer);
		
		String jsonStr = null;
		try {
			jsonStr = new String(buffer,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		JSONObject msg = JSONObject.parseObject(jsonStr);
		return msg;
	}

	public Map<String, Object> decodeHeaderAttch(ByteBuf in) {
		int length = in.readInt();
		if(length == 0){
			return null;
		}
		return decode(in,length);
	}

	private Map<String, Object> decode(ByteBuf in, int length) {
		byte[] buffer = new byte[length];
		in.readBytes(buffer);
		
		String jsonStr = null;
		try {
			jsonStr = new String(buffer,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		JSONObject msg = JSONObject.parseObject(jsonStr);
		return msg;
	}
}
